package middleware

import (
	"github.com/gin-gonic/gin"
	"socket/common"
	"socket/model/user"
	"strings"
)

func AuthMiddle() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		//获取authorization header
		tokenString := ctx.GetHeader("Authorization")

		//验证token  如果token是空的或者不是以bearer开头
		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer ") {
			common.Auth(ctx, "请先登陆", nil)
			ctx.Abort()
			return
		}

		//如果tokenString存在，我们提取token的有效部分
		tokenString = tokenString[7:]

		//解析token是否正确
		token, claims, err := common.ParseToken(tokenString)

		if err != nil || !token.Valid {
			common.Auth(ctx, "请先登陆", nil)
			ctx.Abort()
			return
		}

		//验证通过后获取claims中的UserId
		userId := claims.UserId
		DB := common.GetDB()
		var userList user.User
		DB.First(&userList, userId)

		//判断用户是否存在
		if userList.ID == 0 {
			common.Auth(ctx, "请先登陆", nil)
			ctx.Abort()
			return
		}

		//perUrl := ctx.GetHeader("Per")
		//验证权限
		//var adminMenu auth.AdminMenu
		//DB.Where("uri=?", perUrl).First(&adminMenu)
		//
		////验证权限
		//var adminRole auth.AdminRole
		//DB.First(&adminRole, adminUser.RoleId)
		//if userId != 1 {
		//	if perUrl == "home" || perUrl == "login" {
		//
		//	} else {
		//		menuList := strings.Split(adminRole.Menus, ",")
		//		if common.IsContain(menuList, string(adminMenu.ID)) == false {
		//			ctx.JSON(http.StatusUnauthorized, gin.H{"status_code": 402, "msg": "权限不足"})
		//			ctx.Abort()
		//			return
		//		}
		//	}
		//
		//}

		//如果用户信息存在，将user用户信息写入上下文
		ctx.Set("UserId", userId)
		ctx.Set("UserList", userList)
		ctx.Next()
	}
}
